<?php
namespace app\bis\controller;

use app\admin\extra\Map;
use app\common\facade\Bis;
use app\common\facade\BisAccount;
use app\common\facade\BisLocation;
use app\common\facade\Category;
use app\common\facade\City;
use phpmailer\Email;
use phpmailer\PHPMailer;
use think\Controller;
use think\Request;

class Register extends Controller
{
    public function index()
    {
        // 获取一级城市数据
        $citys = model('City')->getNormalCitysByparentId();

        // 获取一级栏目数据
        $categorys = model('Category')->getNormalCategorysByparentId();
        $this->assign([
            'citys' => $citys,
            'categorys' => $categorys
        ]);
        return $this->fetch();
    }

    public function add(Request $request)
    {
        if (!$request->isPost())
        {
            $this->error('请求错误！');
        }
        $data = $request->post();

        $validate = validate('Bis');
        if (!$validate->scene('add')->check($data))
        {
            $this->error($validate->getError());
        }

        // 获取经纬度
        $lnglat = \Map::getLngLat($data['address']);
        //if (empty($lnglat) || $lnglat['status'] != 0 || $lnglat['result']['precise'] != 1)
        if (empty($lnglat) || $lnglat['status'] != 0)
        {
            $this->error('无法获取数据，或者匹配的地址不精确');
        }

        // 判断提交的管理用户是否已存在
        if (model('BisAccount')->get(['username' => $data['username']]))
        {
            $this->error('该用户已存在，请重新分配');
        }

        // 商户基本信息入库
        $bisData = [
            'name' => $data['name'],
            'city_id' => $data['city_id'],
            'city_path' => empty($data['se_city_id']) ? $data['city_id'] : $data['city_id'].','.$data['se_city_id'],
            'logo' => $data['logo'],
            'licence_logo' => $data['licence_logo'],
            'description' => empty($data['description']) ? '' : $data['description'],
            'bank_info' => $data['bank_info'],
            'bank_user' => $data['bank_user'],
            'bank_name' => $data['bank_name'],
            'faren' => $data['faren'],
            'faren_tel' => $data['faren_tel'],
            'email' => $data['email'],
        ];
        $bisId = model('Bis')->add($bisData);
        // TODO：总店信息校验

        $data['cat'] = '';
        if (!empty($data['se_category_id']))
        {
            $data['cat'] = implode('|', $data['se_category_id']);
        }
        // 总店信息入库
        $locationData = [
            'bis_id' => $bisId,
            'name' => $data['name'],
            'logo' => $data['logo'],
            'tel' => $data['tel'],
            'contact' => $data['contact'],
            'category_id' => $data['category_id'],
            'category_path' => $data['category_id'] . ',' . $data['cat'],
            'city_id' => $data['city_id'],
            'city_path' => empty($data['se_city_id']) ? $data['city_id'] : $data['city_id']. ',' . $data['se_city_id'],
            'api_address' => $data['address'],
            'open_time' => $data['open_time'],
            'content' => empty($data['content']) ? '' : $data['content'],
            'is_main' => 1,
            'xpoint' => empty($lnglat['result']['location']['lng']) ? '' : $lnglat['result']['location']['lng'],
            'ypoint' => empty($lnglat['result']['location']['lat']) ? '' : $lnglat['result']['location']['lat'],
        ];
        $locationId = model('BisLocation')->add($locationData);

        $data['code'] = mt_rand(100, 10000); //自动加盐
        // TODO: 账户信息校验

        $accountData = [
            'bis_id' => $bisId,
            'username' => $data['username'],
            'code' => $data['code'],
            'password' => md5($data['password'].$data['code']),
            'is_main' => 1,
        ];
        $accountId = model('BisAccount')->add($accountData);
        if (!$accountId)
        {
            $this->error('申请失败！');
        }

        // send email
//        $url = $request->domain().url('bis/register/waiting', ['id' => $bisId]);
//        $title = "o2o入驻申请通知";
//        $content = "您提交的入驻请求需等待平台方审核，您可以通过点击连接<a href='".$url."' target='_blank'>查看连接</a> 查看申请状态 <br> 若上方连接无法点击，可以复制连接到浏览器地址栏中访问<br>".$url;
//        $test = Email::send($data['email'], $title, $content);
        $this->success('申请成功！' , url('register/waiting', ['id' => $bisId]));
    }

    public function waiting($id)
    {
        if (empty($id))
        {
            $this->error('error');
        }
        $detail = model('Bis')->get($id);
        $this->assign('detail', $detail);
        return $this->fetch();
    }


}